# Program to find the most common word in a string
string = input("Enter a string: ")
# coding your answer here
# Converting the string to lowercase and splitting it into words
words = string.lower().split()
# Creating a dictionary to store word frequencies
word_freq = {}
# Counting the frequency of each word in the list of words
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# Finding the most common word
most_common_word = max(word_freq, key=word_freq.get)
print("Most common word:", most_common_word)
Appendix J — Assignment 5
J.1 (1) What do the \n
and \t
escape characters represent?
- newline, tab
- space, tab
- newline, backslash
- backslash, space
Ans: Double click to answer the question
J.2 (2) What do the following expressions evaluate to?
'Hello, world!'[3]
, 'Hello, world!'[4:]
, and 'Hello, world!'[:5]
- ‘l’, ‘, world!’, and ‘Hello’
- ‘o’, ‘lo, world!’, and ‘Hello,’
- ‘l’, ‘o’, and ‘, world!’
- ‘l’, ‘o, world!’, and ‘Hello’
Ans: Double click to answer the question
J.3 (3) How can you trim whitespace characters from the beginning or the end of a string?
- lstrip() and rjust()
- center() and rstrip()
- lstrip() and rstrip()
- None of above
Ans: Double click to answer the question
J.4 (4) What do the '-'.join('There can be only one.'.split())
evaluate to?
- ‘There can be only one.’
- ‘There-can be-only-one.’
- ‘There can-be only-one.’
- ‘There-can-be-only-one.’
Ans: Double click to answer the question
J.5 (5) Which of the following methods can be used to check if a string contains only numeric characters?
- isnumeric()
- isnum()
- isdecimal()
- isdigit()
Ans: Double click to answer the question
J.6 (6) How can you access a specific character in a string in Python?
Ans: Double click to answer the question
You can access a specific character in a string in Python using indexing.
J.7 (7) How can you remove all occurrences of a specific character from a string in Python?
Ans: Double click to answer the question
You can remove all occurrences of a specific character from a string in Python using the replace() method. For example, “hello”.replace(“l”, ““) will return”heo”.
J.8 (8) How can you convert a string to a list of characters in Python?
Ans: Double click to answer the question
You can convert a string to a list of characters in Python using list(). For example, list(“hello”) will return [“h”, “e”, “l”, “l”, “o”].
J.9 (9) Write a program that prompts the user to enter a string, and then finds the most common word in the string.
Hint:
1. Convert the string to lowercase and split it into a list of words. 2. Create a dictionary called word_freq
to store the frequency of each word in the list. 3. Find the most common word in the dictionary by using the max()
function with the key argument
set to word_freq.get
, which returns the value associated with each word in the dictionary.
sample output:
Input: `The quick brown fox jumps over the lazy dog. The dog jumps over the fence.`
Output: the
J.10 (10) “Stringy Cards” is a card game that requires players to manipulate strings in order to win. The objective is to have a higher score than the dealer without going over 21.
Rule:
1. Players are dealt two cards face up, and the dealer is dealt two cards, one face up and one face down. 2. The player’s objective is to have a higher score than the dealer without going over 21. 3. Each card has a point value based on its rank. 4. Players can choose to “hit” (take another card) or “stand” (keep their current hand). 5. After each round, the player is given a string to form using the cards in their hand for bonus points. 6. The game continues until the player decides to quit or runs out of cards. 7. The player’s score is tallied at the end, taking into account any bonus points earned or lost during the game. The player with the highest score wins the game.
import random
# Define a list of card ranks and suits
ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
# Initialize a dictionary to store the values of the cards
# coding your answer here
values = {
"Ace": 11,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"10": 10,
"Jack": 10,
"Queen": 10,
"King": 10
}
# Initialize a list to store the deck of cards
deck = []
# Create the deck of cards
for suit in suits:
for rank in ranks:
card = rank + " of " + suit
deck.append(card)
# Shuffle the deck of cards
random.shuffle(deck)
# Deal two cards to the player and the dealer
player_hand = [deck.pop(), deck.pop()]
dealer_hand = [deck.pop(), deck.pop()]
# Initialize variables to keep track of the scores and the game status
player_score = 0
dealer_score = 0
game_over = False
# Helper function to calculate the score of a hand
# coding your answer here
def calculate_score(hand):
score = 0
aces = 0
for card in hand:
rank = card.split()[0]
value = values[rank]
score += value
if rank == "Ace":
aces += 1
while aces > 0 and score > 21:
score -= 10
aces -= 1
return score
# Helper function to print the hands and scores
def print_hands_and_scores():
print("Player's hand: {}, Score: {}".format(", ".join(player_hand), player_score))
print("Dealer's hand: {}, Score: {}".format(", ".join(dealer_hand), dealer_score))
# Main game loop
# coding your answer here
while not game_over:
# Print the hands and scores
print_hands_and_scores()
# Check if the player or the dealer has a blackjack
if player_score == 21:
print("Blackjack! Player wins!")
game_over = True
elif dealer_score == 21:
print("Blackjack! Dealer wins!")
game_over = True
# Ask the player if they want to hit or stand
else:
choice = input("Do you want to hit or stand? ")
if choice.lower() == "hit":
player_hand.append(deck.pop())
player_score = calculate_score(player_hand)
if player_score > 21:
print("Bust! Dealer wins!")
game_over = True
elif choice.lower() == "stand":
dealer_score = calculate_score(dealer_hand)
while dealer_score < 17:
dealer_hand.append(deck.pop())
dealer_score = calculate_score(dealer_hand)
print_hands_and_scores()
if dealer_score > 21:
print("Bust! Player wins!")
game_over = True
elif dealer_score >= player_score:
print("Dealer wins!")
game_over = True
else:
print("Player wins!")
game_over = True